home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Resources / Developers / XAMPP 1.5.4 / Windows installer / xampp-win32-1.5.4-installer.exe / xampp / php / pear / Validate.php < prev    next >
Encoding:
PHP Script  |  2003-10-30  |  16.2 KB  |  448 lines

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2003 The PHP Group                                |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.02 of the PHP license,      |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/2_02.txt.                                 |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Tomas V.V.Cox <cox@idecnet.com>                             |
  17. // |          Pierre-Alain Joye <pajoye@phpindex.com>                     |
  18. // +----------------------------------------------------------------------+
  19. //
  20. // $Id: Validate.php,v 1.30 2003/05/15 10:40:55 pajoye Exp $
  21. //
  22. // Methods for common data validations
  23. //
  24.  
  25. define('VALIDATE_NUM',          '0-9');
  26. define('VALIDATE_SPACE',        '\s');
  27. define('VALIDATE_ALPHA_LOWER',  'a-z');
  28. define('VALIDATE_ALPHA_UPPER',  'A-Z');
  29. define('VALIDATE_ALPHA',        VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
  30. define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'ßΘφ≤·αΦ∞≥∙Σδ∩÷ⁿΓΩε⌠√±τ');
  31. define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . '┴╔═╙┌└╚╠╥┘─╦╧╓▄┬╩╬╘█╤╟');
  32. define('VALIDATE_EALPHA',       VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
  33. define('VALIDATE_PUNCTUATION',  VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
  34. define('VALIDATE_NAME',         VALIDATE_EALPHA . VALIDATE_SPACE . "'");
  35. define('VALIDATE_STREET',       VALIDATE_NAME . "/\\║¬");
  36.  
  37. class Validate
  38. {
  39.     /**
  40.      * Validate a number
  41.      *
  42.      * @param string    $number     Number to validate
  43.      * @param array     $options    array where:
  44.      *                              'decimal'   is the decimal char or false when decimal not allowed
  45.      *                                          i.e. ',.' to allow both ',' and '.'
  46.      *                              'dec_prec'  Number of allowed decimals
  47.      *                              'min'       minimun value
  48.      *                              'max'       maximum value
  49.      */
  50.     function number($number, $options)
  51.     {
  52.         $decimal=$dec_prec=$min=$max= null;
  53.         if(is_array($options)){
  54.             extract($options);
  55.         }
  56.  
  57.         $dec_prec   = $dec_prec ? "{1,$dec_prec}" : '+';
  58.         $dec_regex  = $decimal  ? "[$decimal][0-9]$dec_prec" : '';
  59.  
  60.         if (!preg_match("|^[-+]?\s*[0-9]+($dec_regex)?\$|", $number)) {
  61.             return false;
  62.         }
  63.         if ($decimal != '.') {
  64.             $number = strtr($number, $decimal, '.');
  65.         }
  66.         $number = (float)str_replace(' ', '', $number);
  67.         if ($min !== null && $min > $number) {
  68.             return false;
  69.         }
  70.         if ($max !== null && $max < $number) {
  71.             return false;
  72.         }
  73.         return true;
  74.     }
  75.  
  76.     /**
  77.      * Validate a email
  78.      *
  79.      * @param string    $email          URL to validate
  80.      * @param boolean   $domain_check   Check or not if the domain exists
  81.      */
  82.     function email($email, $check_domain = false)
  83.     {
  84.         if($check_domain){
  85.  
  86.         }
  87.  
  88.         if (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'.'@'.
  89.                  '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'.
  90.                  '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $email))
  91.         {
  92.             if ($check_domain && function_exists('checkdnsrr')) {
  93.                 list (, $domain)  = explode('@', $email);
  94.                 if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
  95.                     return true;
  96.                 }
  97.                 return false;
  98.             }
  99.             return true;
  100.         }
  101.         return false;
  102.     }
  103.  
  104.     /**
  105.      * Validate a string using the given format 'format'
  106.      *
  107.      * @param string    $string     String to validate
  108.      * @param array     $options    Options array where:
  109.      *                              'format' is the format of the string
  110.      *                                  Ex: VALIDATE_NUM . VALIDATE_ALPHA (see constants)
  111.      *                              'min_length' minimum length
  112.      *                              'max_length' maximum length
  113.      */
  114.     function string($string, $options)
  115.     {
  116.         $format = null;
  117.         $min_length = $max_length = 0;
  118.         if (is_array($options)){
  119.             extract($options);
  120.         }
  121.         if ($format && !preg_match("|^[$format]*\$|s", $string)) {
  122.             return false;
  123.         }
  124.         if ($min_length && strlen($string) < $min_length) {
  125.             return false;
  126.         }
  127.         if ($max_length && strlen($string) > $max_length) {
  128.             return false;
  129.         }
  130.         return true;
  131.     }
  132.  
  133.     /**
  134.      * Validate a URL
  135.      *
  136.      * @param string    $url            URL to validate
  137.      * @param boolean   $domain_check   Check or not if the domain exists
  138.      */
  139.     function url($url, $domain_check = false)
  140.     {
  141.         $purl = parse_url($url);
  142.         if (preg_match('|^http$|i', @$purl['scheme']) && !empty($purl['host'])) {
  143.             if ($domain_check && function_exists('checkdnsrr')) {
  144.                 if (checkdnsrr($purl['host'], 'A')) {
  145.                     return true;
  146.                 } else {
  147.                     return false;
  148.                 }
  149.             }
  150.             return true;
  151.         }
  152.         return false;
  153.     }
  154.  
  155.     /**
  156.      * Validate a number according to Luhn check algorithm
  157.      *
  158.      * This function checks given number according Luhn check
  159.      * algorithm. It is published on several places, also here:
  160.      *
  161.      *      http://www.webopedia.com/TERM/L/Luhn_formula.html
  162.      *      http://www.merriampark.com/anatomycc.htm
  163.      *      http://hysteria.sk/prielom/prielom-12.html#3 (Slovak language)
  164.      *      http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html (Perl lib)
  165.      *
  166.      * @param  string  $number number (only numeric chars will be considered)
  167.      * @return bool    true if number is valid, otherwise false
  168.      * @author Ondrej Jombik <nepto@pobox.sk>
  169.      */
  170.     function creditCard($creditCard)
  171.     {
  172.         $creditCard = preg_replace('/[^0-9]/','',$creditCard);
  173.  
  174.         if (empty($creditCard) || ($len_number = strlen($creditCard)) <= 0) {
  175.             return false;
  176.         }
  177.         $sum = 0;
  178.         for ($k = $len_number % 2; $k < $len_number; $k += 2) {
  179.             if ((intval($creditCard{$k}) * 2) > 9) {
  180.                 $sum += (intval($creditCard{$k}) * 2) - 9;
  181.             } else {
  182.                 $sum += intval($creditCard{$k}) * 2;
  183.             }
  184.         }
  185.         for ($k = ($len_number % 2) ^ 1; $k < $len_number; $k += 2) {
  186.             $sum += intval($creditCard{$k});
  187.         }
  188.         return $sum % 10 ? false : true;
  189.     }
  190.  
  191.     /**
  192.      * Validate date and times. Note that this method need the Date_Calc class
  193.      *
  194.      * @param string    $date   Date to validate
  195.      * @param array     $options array options where :
  196.      *                          'format' The format of the date (%d-%m-%Y)
  197.      *                          'min' The date has to be greater
  198.      *                                than this array($day, $month, $year)
  199.      *                          'max' The date has to be smaller than
  200.      *                                this array($day, $month, $year)
  201.      *
  202.      * @return bool
  203.      */
  204.     function date($date, $options)
  205.     {
  206.         $max = $min = false;
  207.         $format = '';
  208.         if (is_array($options)){
  209.             extract($options);
  210.         }
  211.         $date_len   = strlen($format);
  212.         for ($i = 0; $i < strlen($format); $i++) {
  213.             $c = $format{$i};
  214.             if ($c == '%') {
  215.                 $next = $format{$i + 1};
  216.                 switch ($next) {
  217.                     case 'j':
  218.                     case 'd':
  219.                         if ($next == 'j') {
  220.                             $day = (int)Validate::_substr($date, 1, 2);
  221.                         } else {
  222.                             $day = (int)Validate::_substr($date, 2);
  223.                         }
  224.                         if ($day < 1 || $day > 31) {
  225.                             return false;
  226.                         }
  227.                         break;
  228.                     case 'm':
  229.                     case 'n':
  230.                         if ($next == 'm') {
  231.                             $month = (int)Validate::_substr($date, 2);
  232.                         } else {
  233.                             $month = (int)Validate::_substr($date, 1, 2);
  234.                         }
  235.                         if ($month < 1 || $month > 12) {
  236.                             return false;
  237.                         }
  238.                         break;
  239.                     case 'Y':
  240.                     case 'y':
  241.                         if ($next == 'Y') {
  242.                             $year = Validate::_substr($date, 4);
  243.                             $year = (int)$year?$year:'';
  244.                         } else {
  245.                             $year = (int)(substr(date('Y'), 0, 2) .
  246.                                           Validate::_substr($date, 2));
  247.                         }
  248.                         if (strlen($year) != 4 || $year < 0 || $year > 9999) {
  249.                             return false;
  250.                         }
  251.                         break;
  252.                     case 'g':
  253.                     case 'h':
  254.                         if ($next == 'g') {
  255.                             $hour = Validate::_substr($date, 1, 2);
  256.                         } else {
  257.                             $hour = Validate::_substr($date, 2);
  258.                         }
  259.                         if ($hour < 0 || $hour > 12) {
  260.                             return false;
  261.                         }
  262.                         break;
  263.                     case 'G':
  264.                     case 'H':
  265.                         if ($next == 'G') {
  266.                             $hour = Validate::_substr($date, 1, 2);
  267.                         } else {
  268.                             $hour = Validate::_substr($date, 2);
  269.                         }
  270.                         if ($hour < 0 || $hour > 24) {
  271.                             return false;
  272.                         }
  273.                         break;
  274.                     case 's':
  275.                     case 'i':
  276.                         $t = Validate::_substr($date, 2);
  277.                         if ($t < 0 || $t > 59) {
  278.                             return false;
  279.                         }
  280.                         break;
  281.                     default:
  282.                         trigger_error("Not supported char `$next' after % in offset " . ($i+2), E_USER_WARNING);
  283.                 }
  284.                 $i++;
  285.             } else {
  286.                 //literal
  287.                 if (Validate::_substr($date, 1) != $c) {
  288.                     return false;
  289.                 }
  290.             }
  291.         }
  292.         // there is remaing data, we don't want it
  293.         if (strlen($date)) {
  294.             return false;
  295.         }
  296.         if (isset($day) && isset($month) && isset($year)) {
  297.             if (!checkdate($month, $day, $year)) {
  298.                 return false;
  299.             }
  300.             if ($min || $max) {
  301.                 include_once 'Date/Calc.php';
  302.                 if ($min &&
  303.                     (Date_Calc::compareDates($day, $month, $year,
  304.                                              $min[0], $min[1], $min[2]) < 0))
  305.                 {
  306.                     return false;
  307.                 }
  308.                 if ($max &&
  309.                     (Date_Calc::compareDates($day, $month, $year,
  310.                                              $max[0], $max[1], $max[2]) > 0))
  311.                 {
  312.                     return false;
  313.                 }
  314.             }
  315.         }
  316.         return true;
  317.     }
  318.  
  319.     /**
  320.      * Validate a ISBN number
  321.      *
  322.      * This function checks given number according
  323.      *
  324.      * @param  string  $isbn number (only numeric chars will be considered)
  325.      * @return bool    true if number is valid, otherwise false
  326.      * @author Damien Seguy <dams@nexen.net>
  327.      */
  328.     function isbn($isbn)
  329.     {
  330.         if (preg_match("/[^0-9 IXSBN-]/", $isbn)) {
  331.             return false;
  332.         }
  333.  
  334.         if (!ereg("^ISBN", $isbn)){
  335.             return false;
  336.         }
  337.  
  338.         $isbn = ereg_replace("-", "", $isbn);
  339.         $isbn = ereg_replace(" ", "", $isbn);
  340.         $isbn = eregi_replace("ISBN", "", $isbn);
  341.         if (strlen($isbn) != 10) {
  342.             return false;
  343.         }
  344.         if (preg_match("/[^0-9]{9}[^0-9X]/", $isbn)){
  345.             return false;
  346.         }
  347.  
  348.         $t = 0;
  349.         for($i=0; $i< strlen($isbn)-1; $i++){
  350.             $t += $isbn[$i]*(10-$i);
  351.         }
  352.         $f = $isbn[9];
  353.         if ($f == "X") {
  354.             $t += 10;
  355.         } else {
  356.             $t += $f;
  357.         }
  358.         if ($t % 11) {
  359.             return false;
  360.         } else {
  361.             return true;
  362.         }
  363.     }
  364.  
  365.     function _substr(&$date, $num, $opt = false)
  366.     {
  367.         if ($opt && strlen($date) >= $opt && preg_match('/^[0-9]{'.$opt.'}/', $date, $m)) {
  368.             $ret = $m[0];
  369.         } else {
  370.             $ret = substr($date, 0, $num);
  371.         }
  372.         $date = substr($date, strlen($ret));
  373.         return $ret;
  374.     }
  375.  
  376.     function _modf($val, $div) {
  377.         if( function_exists('bcmod') ){
  378.             return bcmod($val,$div);
  379.         } else if (function_exists('fmod')) {
  380.             return fmod($val,$div);
  381.         }
  382.         $r = $a / $b;
  383.         $i = intval($r);
  384.         return intval(($r - $i) * $b);
  385.     }
  386.  
  387.     /**
  388.     * Bulk data validation for data introduced in the form of an
  389.     * assoc array in the form $var_name => $value.
  390.     *
  391.     * @param  array   $data     Ex: array('name'=>'toto','email'='toto@thing.info');
  392.     * @param  array   $val_type Contains the validation type and all parameters used in.
  393.     *                           'val_type' is not optional
  394.     *                           others validations properties must have the same name as the function
  395.     *                           parameters.
  396.     *                           Ex: array('toto'=>array('type'=>'string','format'='toto@thing.info','min_length'=>5));
  397.     * @param  boolean $remove if set, the elements not listed in data will be removed
  398.     *
  399.     * @return array   value name => true|false    the value name comes from the data key
  400.     */
  401.     function multiple(&$data, &$val_type, $remove = false)
  402.     {
  403.         $keys = array_keys($data);
  404.         foreach ($keys as $var_name) {
  405.             if (!isset($val_type[$var_name])) {
  406.                 if ($remove) {
  407.                     unset($data[$var_name]);
  408.                 }
  409.                 continue;
  410.             }
  411.             $opt = $val_type[$var_name];
  412.             $methods = get_class_methods('Validate');
  413.             $val2check = $data[$var_name];
  414.             // core validation method
  415.             if (in_array(strtolower($opt['type']), $methods)) {
  416.                 //$opt[$opt['type']] = $data[$var_name];
  417.                 $method = $opt['type'];
  418.                 $opt = array_slice($opt,1);
  419.  
  420.                 if (sizeof($opt) == 1){
  421.                     $opt = array_pop($opt);
  422.                 }
  423.                 $valid[$var_name] = call_user_func(array('Validate', $method), $val2check,$opt);
  424.  
  425.             /**
  426.              * external validation method in the form:
  427.              * "<class name><underscore><method name>"
  428.              * Ex: us_ssn will include class Validate/US.php and call method ssn()
  429.              */
  430.             } elseif (strpos($opt['type'],'_') !== false) {
  431.                 list($class, $method) = explode('_', $opt['type'], 2);
  432.                 $class = strtoupper($class);
  433.                 @include_once("Validate/$class.php");
  434.                 if (!class_exists("Validate_$class") ||
  435.                     !in_array($method, get_class_methods("Validate_$class"))) {
  436.                     trigger_error("Invalid validation type Validate_$class::$method", E_USER_WARNING);
  437.                     continue;
  438.                 }
  439.                 $valid[$var_name] = call_user_func(array("Validate_$class", $method), $data[$var_name]);
  440.             } else {
  441.                 trigger_error("Invalid validation type {$opt['type']}", E_USER_WARNING);
  442.             }
  443.         }
  444.         return $valid;
  445.     }
  446. }
  447. ?>
  448.